package com.chat.simplechat.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangyabin
 * @date 2021/7/16 14:21
 */
public class TokenBuilder {

    //过期时长 60秒
    private static final long EXPIRE_TIME = 360 * 60 * 1000;

    //私钥
    public static final String SECRET = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 生成token
     * @param userParam
     * @return
     * @throws Exception
     */
    public static String createToken(Map<String,String> userParam) {
        //签发时间
        Date iatDate = new Date();
        //过期时间
        Date expiresDate = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        Map<String,Object> map = new HashMap<>();
        map.put("alg","HS256");
        map.put("type","jwt");
        JWTCreator.Builder builder = 
                JWT.create().withHeader(map).withExpiresAt(expiresDate).withIssuedAt(iatDate);
        for(Map.Entry<String,String> entry:userParam.entrySet()){
            builder.withClaim(entry.getKey(),entry.getValue());
        }
        String token = builder.sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 刷新token过期时间
     * @param token
     * @return
     */
    public static String refreshToken(String token){
        DecodedJWT jwt = JWT.decode(token);
        Map<String,Claim> claimMap = jwt.getClaims();
        Map<String,String> map = new HashMap<>();
        for (Map.Entry<String,Claim> entry:claimMap.entrySet()){
            map.put(entry.getKey(),entry.getValue().asString());
        }
        return createToken(map);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static Map<String,String> verifyToken(String token){
        Map res = new HashMap();
        String msg = "";
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            DecodedJWT jwt = verifier.verify(token);
            Map<String, Claim> claimMap = jwt.getClaims();
            if(null != claimMap){
                for(Map.Entry<String,Claim> entry:claimMap.entrySet()){
                    res.put(entry.getKey(),entry.getValue().asString());
                }
            }
        } catch (JWTVerificationException e) {
            msg = "校验令牌失败:令牌过期,系统重新设置令牌!";
            throw new RuntimeException(msg);
        } catch (Exception e) {
            msg = "校验令牌失败:验证签名失败!";
            throw new RuntimeException(msg);
        }
        return res;
    }

    
    public static void main(String[] args) {
        Map<String,String> userInfo = new HashMap<>();
        userInfo.put("userId","101");
        userInfo.put("userName","syasuo");
        String token = TokenBuilder.createToken(userInfo);
        System.out.println(token);
        String s = "eyJ0eXAiOiJKV1QiLCJ0eXBlIjoiand0IiwiYWxnIjoiSFMyNTYifQ.eyJleHAiOjE2MjY0MDQ3MTUsInVzZXJOYW1lIjoic3lhc3VvIiwiaWF0IjoxNjI2NDA0NTY1LCJ1c2VySWQiOiIxMDEifQ.AKWWPwy-yu7ixfmLCN7ex48iaqCMwSFz-bkgsbjLJck";
        /*Map<String,String> map = TokenBuilder.verifyToken(s);
        System.out.println(map.get("userId")+":"+map.get("userName"));*/
        String newToken = refreshToken("eyJ0eXAiOiJKV1QiLCJ0eXBlIjoiand0IiwiYWxnIjoiSFMyNTYifQ.eyJleHAiOjE2MjY0MDQ3MTUsInVzZXJOYW1lIjoic3lhc3VvIiwiaWF0IjoxNjI2NDA0NTY1LCJ1c2VySWQiOiIxMDEifQ.AKWWPwy-yu7ixfmLCN7ex48iaqCMwSFz-bkgsbjLJck");
        Map<String,String> temp = TokenBuilder.verifyToken(newToken);
        System.out.println(temp.get("userId")+":"+temp.get("userName"));
    }
}
